﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Threading;
using TestPlatform.Core;

namespace TestPlatform.Performer.Mssql
{
    public class MssqlHelper : IDatabaseHelper
    {
        public const string DefaultConnectionString = @"Server=.\MSSQL2008;Initial Catalog=MGR-Database;Integrated Security=true";        

        public static SqlConnection CreateConnection()
        {
            SqlConnection c = new SqlConnection(DefaultConnectionString);
            c.Open();

            return c;
        }

        public List<Guid> SeedDatabase(int count)
        {
            List<Guid> ids = new List<Guid>();

            using (SqlConnection c = MssqlHelper.CreateConnection())
            {
                for (int i = 0; i < count; i++)
                {
                    Guid userId = Guid.NewGuid();

                    SqlCommand cmd = c.CreateCommand();
                    cmd.CommandText = string.Format("INSERT INTO [Users](Id, Login, Name) VALUES('{0}', '{1}', '{2}')", userId, userId, userId);
                    cmd.ExecuteNonQuery();

                    ids.Add(userId);
                }
            }

            return ids;
        }

        public void ClearDatabase()
        {
            using (var c = MssqlHelper.CreateConnection())
            {
                SqlCommand cmd = c.CreateCommand();

                cmd.CommandText = "DELETE FROM [Posts]";
                cmd.ExecuteNonQuery();

                cmd = c.CreateCommand();

                cmd.CommandText = "DELETE FROM [Users]";
                cmd.ExecuteNonQuery();
            }
        }
    }
}
